package com.nail.api.customMake.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.nail.api.customMake.bean.Indent;
import com.nail.utils.PageResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nail.api.customMake.bean.Message;
import com.nail.api.customMake.dao.IMessageDao;
import com.nail.api.customMake.service.IMessageService;

import java.util.List;
import java.util.Map;

@Service("messageService")
public class MessageServiceImpl implements IMessageService {
	Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private IMessageDao messageDao;
	
	@Transactional
	public void addMessage(Message message){
		messageDao.insertSelective(message);
	}
	
	@Transactional
	public void setIsRead(String messageId){
		messageDao.setIsRead(messageId);
	}
	
	@Transactional
	public List<Message> setIsReadAndGetData(String messageId,Long userId,Integer start,Integer end){
		messageDao.setIsRead(messageId);
		return messageDao.getUnReadMessageByUserId(userId, start, end);
	}

	public PageResult getMessageByUserId(Long userId,PageResult pageResult){
		List<Message> list;
		if(userId != null) {
			list = messageDao.getMessageByUserId(userId, pageResult.getBegin(), pageResult.getPageSize());
			Integer num = messageDao.getMessageByUserIdCount(userId);
			pageResult.setTotalNum(num);
		}else{
			list = messageDao.getMessage(pageResult.getBegin(), pageResult.getPageSize());
            Integer num = messageDao.getMessageCountAll();
            pageResult.setTotalNum(num);
		}
		pageResult.setData(list);
		return pageResult;
	}
	
	
	public PageResult getMessageByCondition(Long userId,PageResult pageResult,String condition){
		List<Message> list;
		
		StringBuffer seachSQL = new StringBuffer("select * from message where 1=1");
		StringBuffer countSQL = new StringBuffer("select count(1) from message where 1=1");
		
		Map<String, Object> map = JSONObject.parseObject(condition);
		
		if(userId != null){
			seachSQL.append(" and user_id ="+userId);
			countSQL.append(" and user_id ="+userId);
		}
		
		if(!map.isEmpty()){
			if(map.get("isRead") != null){
				seachSQL.append(" and is_read =" + map.get("isRead"));
				countSQL.append(" and is_read =" + map.get("isRead"));
			}
			
			if(map.get("accepter") != null){
				seachSQL.append(" and accepter =" + map.get("accepter"));
				countSQL.append(" and accepter =" + map.get("accepter"));
			}
		}


		seachSQL.append(" ORDER BY is_read ASC,create_time DESC");


		list = messageDao.selectSQL(seachSQL.toString());
		Integer num = messageDao.CountSQL(countSQL.toString());
		pageResult.setTotalNum(num);
		
		pageResult.setData(list);
		return pageResult;
	}
	
}
